package org.lanplay.server.entitymodel;

import java.io.Serializable;

import javax.persistence.EntityManager;

import org.hibernate.proxy.HibernateProxy;

import com.google.inject.Inject;
import com.google.inject.Provider;

public class EntityModel<T extends Identifiable<?>> extends
		AbstractEntityModel<T> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Inject
	private transient final Provider<EntityManager> emp;

	public EntityModel(Provider<EntityManager> em, T entity) {
		super(unproxy(entity));
		emp = em;
	}

	public EntityModel(Provider<EntityManager> em, Class<? extends T> clazz,
			Serializable id) {
		super(clazz, id);
		emp = em;
	}

	@SuppressWarnings("unchecked")
	@Override
	protected T load(Class<?> clazz, Serializable id) {
		return unproxy(emp.get().find((Class<T>) clazz, id));
	}

	@SuppressWarnings("unchecked")
	private static <T extends Identifiable<?>> T unproxy(T entity) {
		if (entity instanceof HibernateProxy) {
			entity = (T) ((HibernateProxy) entity)
					.getHibernateLazyInitializer().getImplementation();
		}
		return entity;
	}

}
